package com.yunxiao.cloud.auth.server.support;

import com.yunxiao.cloud.auth.server.entity.SysPermission;
import com.yunxiao.cloud.auth.server.entity.SysRole;
import com.yunxiao.cloud.auth.server.entity.SysUser;
import com.yunxiao.cloud.auth.server.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: MyUserDetailsService
 * @author: yunxiao
 * @date: 2020/2/18 13:54
 * @version: V1.0
 **/
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 授权的时候是对角色授权，
     * 而认证的时候应该基于资源，而不是角色，
     * 因为资源是不变的，而用户的角色是会变的
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getUserByName(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException(username);
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (SysRole role : sysUser.getSysRoleList()) {
            for (SysPermission permission : role.getSysPermissionList()) {
                authorities.add(new SimpleGrantedAuthority(permission.getCode()));
            }
        }

        return new User(sysUser.getUsername(), sysUser.getPassword(), authorities);
    }
}
